package com.zyf.user.config;


import com.zyf.user.service.impl.RoleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
/*
ps:这东西就是把你访问的url的权限拿出来，然后找到对应的角色，传上去
 */
@Component
public class FilterInvocationSecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {
    @Autowired
    RoleServiceImpl roleService;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String RequestUrl=((FilterInvocation)o).getRequestUrl();
        int x=RequestUrl.indexOf("?");
        if (x>0){
            RequestUrl=RequestUrl.substring(0,x);
        }
//        if ("/login".equals(RequestUrl)||"logout".contains(RequestUrl)){
//            return null;
//        }
//        暂时用RequestUrl作为权限
        List<String> listRole = roleService.selectRoleByUrl(RequestUrl);
        if(listRole.size()==0){
            String[] string=new String[]{"ROLE_TOURIST"};
            return SecurityConfig.createList(string);
        }
        String[] strings=new String[listRole.size()];
        for (int i=0;i<listRole.size();i++){
            strings[i]=listRole.get(i);
        }
        return SecurityConfig.createList(strings);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}

